package com.plian.system.service.fr.budgetadjustment.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.BigDecimalUtil;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.dao.fr.budgetadjustment.BudgetAdjustmentDao;
import com.plian.system.dao.fr.gsalaryslip.GsalarySlipDao;
import com.plian.system.entity.fr.adjustment.AdjustmentReportRelation;
import com.plian.system.entity.fr.report.ReportColumnValue;
import com.plian.system.entity.fr.report.ReportLink;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.service.fr.adjustment.IAdjustmentReportRelationService;
import com.plian.system.service.fr.adjustment.IAdjustmentTableVersionService;
import com.plian.system.service.fr.budgetadjustment.INewBudgetAdjustmentService;
import com.plian.system.service.fr.report.IReportColumnValueService;
import com.plian.system.service.fr.report.IReportLinkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: gangan
 * @create: 2021-09-15 14:17
 */
@Service
@Slf4j
public class NewBudgetAdjustmentServiceImpl implements INewBudgetAdjustmentService {

    @Autowired
    private BudgetAdjustmentDao budgetAdjustmentDao;

    @Autowired
    private GsalarySlipDao gsalarySlipDao;

    @Autowired
    private IAdjustmentTableVersionService adjustmentTableVersionService;

    @Autowired
    private IAdjustmentReportRelationService adjustmentReportRelationService;

    @Autowired
    private IReportColumnValueService reportColumnValueService;

    @Autowired
    private IReportLinkService reportLinkService;

    private final static String C2 = "c2";

    private final static String C4 = "c4";

    @Override
    public ListResult<PageData> findGsalaryValue(PageData pageData) {
        try {
            PageData adjustmentTable = budgetAdjustmentDao.findZbById(pageData);
            String orgId = pageData.getString("orgId");
            String year = adjustmentTable.getString("year");
            String version = adjustmentTableVersionService.getVersion(year);
            pageData.put("version", version);
            PageData tableInfo = budgetAdjustmentDao.findorgname(pageData);

            pageData.put("version", version);

            PageData gsalaryTable = gsalarySlipDao.findzb(adjustmentTable);

            if (gsalaryTable == null){
                ListResult<PageData> result = new ListResult<>(CommonCode.FAIL);
                result.setMessage("此年度未填报相关数据");
                return result;
            }
            List<ReportLink> reportLinks = reportLinkService.list(new LambdaQueryWrapper<ReportLink>()
                    .eq(ReportLink::getId, gsalaryTable.getString("id")));
            Map<String, String> orgLinkMap = reportLinks.stream().collect(Collectors.toMap(ReportLink::getOrgId, ReportLink::getLinkId, (a, b) -> a));
            List<AdjustmentReportRelation> reportAdjustmentRelations =  adjustmentReportRelationService
                    .list(new LambdaQueryWrapper<AdjustmentReportRelation>()
                    .eq(AdjustmentReportRelation::getAdjustmentTableName, orgId)
                    .eq(AdjustmentReportRelation::getVersion, version)
                    .orderByAsc(AdjustmentReportRelation::getAdjustmentLines));
            if (CollectionUtil.isEmpty(reportAdjustmentRelations)){
                ListResult<PageData> result = new ListResult<>(CommonCode.FAIL);
                result.setMessage("调整表和预算表关系配置有问题，请联系管理员!");
                return result;
            }

            LambdaQueryWrapper<ReportColumnValue> valueQueryWrapper = new LambdaQueryWrapper<>();
            int count = 0;
            for (int i = 0; i< reportAdjustmentRelations.size(); i++){
                AdjustmentReportRelation adjustmentReportRelation = reportAdjustmentRelations.get(i);
                if (!orgLinkMap.containsKey(adjustmentReportRelation.getReportTableName())){
                   continue;
                }
                String linkId = orgLinkMap.get(adjustmentReportRelation.getReportTableName());
                //todo 考虑公式取值
                if ("2.0".equals(version) &&
                        "ta2021_16_1".equals(adjustmentReportRelation.getAdjustmentTableName()) &&
                        "co2021_161_3".equals(adjustmentReportRelation.getAdjustmentColumnId()) &&
                        "34".equals(adjustmentReportRelation.getAdjustmentLines())){
                    valueQueryWrapper.or(wrapper -> wrapper.eq(ReportColumnValue::getLinkId, linkId)
                            .eq(ReportColumnValue::getColumnId, "co2021_7_5")
                            .eq(ReportColumnValue::getOrderNumber, "7"));
                    valueQueryWrapper.or(wrapper -> wrapper.eq(ReportColumnValue::getLinkId, linkId)
                            .eq(ReportColumnValue::getColumnId, "co2021_7_6")
                            .eq(ReportColumnValue::getOrderNumber, "7"));

                }
                valueQueryWrapper.or(wrapper -> wrapper.eq(ReportColumnValue::getLinkId, linkId)
                        .eq(ReportColumnValue::getColumnId, adjustmentReportRelation.getReportColumnId())
                        .eq(ReportColumnValue::getOrderNumber, adjustmentReportRelation.getReportLines()));
                count++;
            }


            if (count == 0){
                ListResult<PageData> result = new ListResult<>(CommonCode.FAIL);
                result.setMessage("此年度未填报相关数据");
                return result;
            }
            List<ReportColumnValue> values = reportColumnValueService.list(valueQueryWrapper);
            Map<String, ReportColumnValue> reportColumnValueMap = values.stream().collect(Collectors.toMap(value -> value.getColumnId() + "_" + value.getOrderNumber(), value -> value, (a,b) -> a));


            int startChangeLineNumber = tableInfo.getInteger("startChangeLineNumber");
            List<PageData> results = new ArrayList<>();
            if (startChangeLineNumber > 0){
                for (int i = 1; i < startChangeLineNumber; i++){
                    PageData initMap = new PageData();
                    initMap.put(C2, "");
                    initMap.put(C4, "");
                    results.add(initMap);
                }
            }
            int lastIndex = 0;
            for (AdjustmentReportRelation adjustmentReportRelation : reportAdjustmentRelations){
                int index = Integer.valueOf(adjustmentReportRelation.getAdjustmentLines());
                if (lastIndex != 0 &&  index > lastIndex + 1){
                    for (int i = lastIndex + 1; i < index; i++){
                        PageData initMap = new PageData();
                        initMap.put(C2, "");
                        initMap.put(C4, "");
                        results.add(initMap);
                    }
                }
                lastIndex = index;


                PageData valueMap = new PageData();
                valueMap.put(C2, "");
                valueMap.put(C4, "");
                String key = adjustmentReportRelation.getReportColumnId() + "_" + adjustmentReportRelation.getReportLines();
                if (reportColumnValueMap.containsKey(key)){
                    if ("2.0".equals(version) &&
                            "ta2021_16_1".equals(adjustmentReportRelation.getAdjustmentTableName()) &&
                            "co2021_161_3".equals(adjustmentReportRelation.getAdjustmentColumnId()) &&
                            "34".equals(adjustmentReportRelation.getAdjustmentLines())){
                        String key1 = "co2021_7_5" + "_" + "7";
                        String key2 = "co2021_7_6" + "_" + "7";
                        ReportColumnValue value1 = reportColumnValueMap.get(key1);
                        ReportColumnValue value2 = reportColumnValueMap.get(key2);
                        valueMap.put(C2, BigDecimalUtil.add(BigDecimalUtil.toBigdecimal(value1.getReplyValue()), BigDecimalUtil.toBigdecimal(value2.getReplyValue())));
                        valueMap.put(C4, BigDecimalUtil.add(BigDecimalUtil.toBigdecimal(value1.getReplyValue()), BigDecimalUtil.toBigdecimal(value2.getReplyValue())));
                    }else {
                        ReportColumnValue reportColumnValue = reportColumnValueMap.get(key);
                        valueMap.put(C2, reportColumnValue.getReplyValue());
                        valueMap.put(C4, reportColumnValue.getReplyValue());
                    }
                }
                results.add(valueMap);
            }

            ListResult<PageData> result = new ListResult<>(CommonCode.SUCCESS);
            result.setList(results);
            return result;
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException("系统错误");
        }

    }
}
